import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

import '../config/net_work_config.dart';
import '../util/sp_util.dart';
import 'event_bus.dart';

/// 请求工具类
class RequestClient {
  late Dio _dio;

  factory RequestClient() {
    return RequestClient._internal();
  }

  RequestClient._internal() {
    var token = SpUtil.getString("token", defValue: "");

    ///初始化 dio 配置
    var options = BaseOptions(
        baseUrl: NetWorkConfig.baseUrl,
        connectTimeout: NetWorkConfig.connectTimeOut,
        receiveTimeout: NetWorkConfig.readTimeOut,
        sendTimeout: NetWorkConfig.writeTimeOut,
        headers: token == "" ? {} : {"token": "$token"}
        );
    _dio = Dio(options);
    _dio.interceptors.add(InterceptorsWrapper(
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
          if (kDebugMode) {
            debugPrint("请求地址：${options.path}");
            debugPrint("请求参数：${options.queryParameters}");
            debugPrint("请求头：${options.headers}");
            debugPrint("请求体：${options.data}");
          }
          return handler.next(options);
        }));
    _dio.interceptors.add(InterceptorsWrapper(
        onResponse: (Response response, ResponseInterceptorHandler handler) {
          if (kDebugMode) {
            debugPrint("响应状态码：${response.statusCode}");
            debugPrint("响应头：${response.headers}");
            debugPrint("响应体：${response.data}");
          }
          if(response.statusCode == 401 || response.data["code"] == 401){
            //跳转到登录
            bus.emit("logout");
          }else{
            handler.next(response);
          }
        }));
  }

  /// Handy method to make http GET request, which is a alias of  [BaseDio.request].
  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onReceiveProgress,
  }) async {
    // Store store = await Store.getInstance();
    // _dio.options.headers.addAll({"token": "${await store.getString(StoreKeys.token)}"});

    return _dio.get(path,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onReceiveProgress: onReceiveProgress);
  }

  /// Handy method to make http POST request, which is a alias of  [BaseDio.request].
  Future<Response<T>> post<T>(
    String path, {
    data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    // Store store = await Store.getInstance();
    // _dio.options.headers.addAll({"token": store.getString(StoreKeys.token)});
    Response<T> future = await _dio.post(path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress);
    if (kDebugMode) {
      print(future.statusCode);
    }
    return future;
  }

  /// Handy method to make http POST request, which is a alias of  [BaseDio.request].
  Future<Response<T>> postForm<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    _dio.options.contentType =Headers.formUrlEncodedContentType;
    // Store store = await Store.getInstance();
    // _dio.options.headers.addAll({"token": store.getString(StoreKeys.token)});
    return _dio.post(path,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress);
  }
}
